//
//  UserProfileApi.swift
//  FeastBooking
//
//  Created by Imon on 2017/11/24.
//  Copyright © 2017年 Imon. All rights reserved.
//

import Foundation
import Moya

enum UserProfileApi {
    case getProfile()
    case postAvatar(avatar: UIImage)
    case changeEmail(emailToken: String)
    case changePassword(password: String, newPassword: String)
    case changePhone(phone: String)
}

extension UserProfileApi: TargetType {
    
    var baseURL: URL {
        return URL(string: serverBasePath)!
    }
    
    var path: String {
        switch self {
        case .getProfile:
            return "/user/profile"
        case .postAvatar:
            return "/user/profile/avatar"
        case .changeEmail:
            return "/user/profile/email"
        case .changePassword:
            return "/user/profile/password"
        case .changePhone:
            return "/user/profile/phone"
        }
    }
    
    var method: Moya.Method {
        switch self {
        case .getProfile:
            return .get
        case .postAvatar:
            return .post
        case .changeEmail, .changePassword, .changePhone:
            return .put
        }
    }
    
    var parameters: [String: Any]? {
        switch self {
        case .changeEmail(let emailToken):
            return ["value": emailToken]
        case .changePassword(let password, let newPassword):
            return ["newPassword": newPassword, "password": password]
        case .changePhone(let phone):
            return ["value": phone]
        default:
            return nil
        }
    }
    
    var task: Task {
        switch self {
        case .postAvatar(let avatar):
            let form: [MultipartFormData] = buildFormDataFromImage(avatar: avatar)
            return .upload(.multipart(form))
        default:
            return .request
        }        
    }
    
    var sampleData: Data {
        return "{\"data\":{\"msg\":\"good\"},\"meta\":{\"status\":200,\"msg\":\"OK\"}}".data(using: String.Encoding.utf8)!
    }
    
    var parameterEncoding: ParameterEncoding {
        switch self {
        case .changeEmail, .changePassword, .changePhone:
            return JSONEncoding.default
        default:
            return URLEncoding.default
        }
    }
}

func buildFormDataFromImage(avatar: UIImage) -> [MultipartFormData] {
    var result: [MultipartFormData] = []
    let imageData: Data = avatar.compressImage(image: avatar, maxLength: imageMaxSize)!
    result.append(MultipartFormData(provider: .data(imageData), name: "file", fileName: "avatar.jpg", mimeType: "image/jpeg"))
    return result
}
